package com.yumeng.framework.auth.shiro.filter.cus;

import com.yumeng.common.data.enums.AuthClientType;
import com.yumeng.common.data.enums.AuthMode;
import com.yumeng.common.helper.BaseEnumHelper;
import com.yumeng.framework.auth.shiro.token.MyUsernamePasswordToken;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;

/**
 *
 * @author wxd
 * @date 2025/11/11 09:43
 */
public class CustomFormAuthenticationFilter extends FormAuthenticationFilter {

    //非jwt环境下的认证，目前此clientType暂未适配业务逻辑
    /** 客户端类型参数 */
    @Setter
    private String clientTypeParameter = "clientType";

    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
        String clientTypeStr = getClientType(request);
        AuthClientType clientType = StringUtils.isNotBlank(clientTypeStr) ?
                BaseEnumHelper.getEnum(AuthClientType.class, Integer.parseInt(clientTypeStr), true) : AuthClientType.getDefault();
        AuthenticationToken token = super.createToken(request, response);
        if (token instanceof UsernamePasswordToken upToken){
            return new MyUsernamePasswordToken(upToken, AuthMode.NORMAL, clientType);
        }else {
            throw new AuthenticationException("token类型未知");
        }
    }

    protected String getClientType(ServletRequest request) {
        return WebUtils.getCleanParam(request, clientTypeParameter);
    }
}
